//
//  MCDistributionViewController.swift
//  StoreManage
//
//  Created by MC on 2018/6/20.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit
import SDWebImage

typealias MCDistributionViewControllerClosure = (UIViewController) -> Void

class MCDistributionViewController: MCViewController {
    
    
    public var marketingType = 0  // 分销类别：0：进行中，1：已完成
    
    private var pageNumber = 1
    
    var closure : MCDistributionViewControllerClosure?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        sendNetworking()
    }
    
    // MARK: - Setter & Getter
    lazy private var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.backgroundColor = UIColor.MCGray_light
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    lazy var dataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
}

extension MCDistributionViewController : UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArrayM.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = self.dataArrayM[indexPath.row] as! MCDistributionModel
        return model.cellHeight
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = MCDistributionCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
        cell.marketingType = marketingType
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        cell.backgroundColor = UIColor.MCGray_light
        cell.closure = { vc  in
            self.closure?(vc)
        }
        
        cell.shareClosure = { activityLogId in
            self.WXShare(activityLogId: activityLogId)
        }
        
        cell.model = self.dataArrayM[indexPath.row] as! MCDistributionModel
        
        
        return cell
    }
}


//MARK: 通知回调，闭包回调，点击事件
extension MCDistributionViewController {
    @objc func addButtonClicked() {
        let vc = MCAddCommunityViewController()
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    
    
    @objc func WXShare(activityLogId:Int) {
        
        sendNetworking_shareWithActivityLogId(activityLogId)
    }
}


//MARK: 网络请求
extension MCDistributionViewController {
    func sendNetworking() {
        let para = [
            "marketingType" : marketingType,
            "pageNum" : pageNumber
            ] as [String : Any]
        
        
        MCNetwork.POST(JAVA_findMyMarketing, para, vc: self, success: { (data) in

            let dataArray = data.arrayObject ?? []
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            if self.pageNumber == 1 {
                self.dataArrayM.removeAllObjects()
                self.tableView.mj_footer.resetNoMoreData()
            }
            
            if dataArray.count == 0 {
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            }
            
            if dataArray.count + self.dataArrayM.count == 0 {
                self.tableView.showBgImage()
            } else {
                self.tableView.hideBgImage()
                for dict in dataArray {
                    let model = MCDistributionModel()
                    model.setValuesForKeys(dict as? [String:Any] ?? [:])
                    self.dataArrayM.add(model)
                }
                self.tableView.reloadData()
            }
            
        }, failure: nil)
    }
    
    func sendNetworking_shareWithActivityLogId(_ activityLogId:Int) {
        let para = [
            "activityLogId" : activityLogId
            ] as [String : Any]
        
        
        MCNetwork.POST(JAVA_findShareLinkContent, para, vc: self, success: { (data) in
            
            let dataDict = data.dictionaryObject ?? [:]
            let imgPath = dataDict["imgPath"] as? String ?? ""
            
            let manager = SDWebImageManager.init()
            manager.imageDownloader?.downloadImage(with: URL.init(string: imgPath), options: SDWebImageDownloaderOptions(rawValue: 0), progress: { (_, _, _) in
                
            }, completed: { (image, _, _, _) in
                
                let alter = UIAlertController.init(title: "微信分享", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
                let cancle = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.cancel) { (a) in
                    
                }
                let one = UIAlertAction.init(title: "微信好友", style: UIAlertActionStyle.default) { (b) in
                    MCWXShare_image(image: image!, compressionQuality: 1, scane: WXSceneSession)
                }
                
                let two = UIAlertAction.init(title: "微信朋友圈", style: UIAlertActionStyle.default) { (b) in
                    MCWXShare_image(image: image!, compressionQuality: 1, scane: WXSceneTimeline)
                }
                alter.addAction(cancle)
                alter.addAction(one)
                alter.addAction(two)
                self.present(alter, animated: true, completion: nil)
                
            })

            
        }, failure: nil)
    }
}

//MARK: UI的处理,通知的接收
extension MCDistributionViewController {
    func baseSetting() {
        
        self.view.backgroundColor = UIColor.MCGray_light
        
        self.tableView.mj_header = MCRefreshHeader.init(refreshingBlock: {
            self.pageNumber = 1
            self.sendNetworking()
        })
        
        self.tableView.mj_footer = MCRefreshFooter.init(refreshingBlock: {
            self.pageNumber += 1
            self.sendNetworking()
        })
    }
    
    func initUI() {
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view).inset(UIEdgeInsetsMake(0, 0, MCSafeAreaBottomHeight, 0))
        }
    }

}

